package com.springboot.demo.thread_pool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

/**
 * countDownLatchDemo
 *
 * @author supu
 * @date 2019-03-26 10:36
 **/
public class CountDownLatchDemo {
    private final Map<String,Integer> countMap = new ConcurrentHashMap<>(1);
    private final CountDownLatch latch = new CountDownLatch(5);

    @Test
    public void countDownLatchTest() throws InterruptedException {
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                long start = System.currentTimeMillis();
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                latch.countDown();
                System.out.println(Thread.currentThread().getName() + " : " + (System.currentTimeMillis() - start));
            },"thread"+i).start();
        }

        latch.await();
    }

    public static void main(String[] args) {
        CountDownLatchDemo demo = new CountDownLatchDemo();
        demo.runTest();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("重新进入*****************");



        demo.runTest();
    }

    private void runTest(){
        for(int i=0; i< 5; i++){
            new Thread(() -> {
                try {
                    synchronized (countMap) {
                        countMap.put("test", countMap.get("test") == null ? 1 : (countMap.get("test") + 1));
                        System.out.println(Thread.currentThread().getName() + " count:" + countMap.get("test"));
                    }
                    latch.countDown();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /*countMap.forEach((key,value) -> {
            System.out.println(key + "---" + value);
        });*/
        System.out.println("latchCount:" + latch.getCount());

        System.out.println("testCount:" + countMap.get("test"));

    }

}
